package com.mr.shop.web;

import com.baidu.shop.base.BaseApiService;
import com.baidu.shop.base.Result;
import com.baidu.shop.dto.UserInfo;
import com.baidu.shop.entity.UserEntity;
import com.baidu.shop.status.HTTPStatus;
import com.baidu.shop.utils.CookieUtils;
import com.baidu.shop.utils.JwtUtils;
import com.mr.shop.business.UserOauthService;
import com.mr.shop.config.JwtConfig;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description:
 * @ClassName: UserOauthController
 * @Author: User
 * @date: 2020.10.15 17:51
 * @version: 1.0
 */
@RestController
public class UserOauthController extends BaseApiService {

    @Resource
    private UserOauthService userOauthService;

    @Resource
    private JwtConfig jwtConfig;

    @PostMapping("/oauth/login")
    public Result<JSONObject> login(@RequestBody UserEntity userEntity , HttpServletRequest request,
                                    HttpServletResponse response){
        String token = userOauthService.checkUser(userEntity,jwtConfig);
        if (token==null){
            return this.setResultError(HTTPStatus.ERROR, "账号密码错误");
        }
        CookieUtils.setCookie(request, response, jwtConfig.getCookieName(), token,jwtConfig.getCookieMaxAge() ,true);
        return  this.setResultSuccess();
    }

    @GetMapping("/oauth/verify")
    public Result<JSONObject> verify(@CookieValue(value = "MRSHOP_TOKEN") String cookie,
                                     HttpServletResponse response,HttpServletRequest request){
        UserInfo infoFromToken=null;
        try {
             infoFromToken = JwtUtils.getInfoFromToken(cookie, jwtConfig.getPublicKey());

            String token = JwtUtils.generateToken(infoFromToken, jwtConfig.getPrivateKey(), jwtConfig.getExpire());
            CookieUtils.setCookie(request, response, jwtConfig.getCookieName(),token,jwtConfig.getCookieMaxAge(),true);
        } catch (Exception e) {
            e.printStackTrace();
            return this.setResultError(HTTPStatus.USER_VALIDATE_ERROR, "登录失效");
        }
        return  this.setResultSuccess(infoFromToken);
    }

}
